﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;

namespace DataAccess
{
    public class UserRepository : ConnectionClass
    {
        public UserRepository()
            : base()
        {
 
        }

        public void AddUser(User u)
        {
            db.AddToUsers(u);
            u.Roles.Add(GetRole(1));
            db.SaveChanges();
        }

        public Role GetRole(int id)
        {
            return db.Roles.SingleOrDefault(x => x.ID == id);
        }

        public IEnumerable<Role> GetAllUserRoles(string username)
        {
            return GetUserByUserName(username).Roles;
        }

        public bool CheckEmailExists(string email)
        {
            bool found = false;
            foreach (User u in db.Users)
            {
                if (u.Email == email)
                {
                    found = true;
                }
            }

            return found;
        }

        public bool CheckUserNameExists(string UserName)
        {
            bool found = false;
            foreach (User u in db.Users)
            {
                if (u.UserName == UserName)
                {
                    found = true;
                }
            }

            return found;
        }

        public User GetUserByUserName(string username)
        {
            return db.Users.SingleOrDefault(o => o.UserName == username);
        }

        public void DeleteUser(string UserName)
        {
            db.Users.DeleteObject(GetUserByUserName(UserName));
        }

        public IEnumerable<User> GetAllUsers()
        {
            return db.Users;
        }

        public void UpdateUser(User u)
        {
            User OU = GetUserByUserName(u.UserName);
            db.Users.Attach(OU);
            db.Users.ApplyCurrentValues(u);
            db.SaveChanges();
        }

        public bool UserLogin(string UserName, string Password)
        {
            if (db.Users.SingleOrDefault(u => u.UserName == UserName && u.Password == Password) != null)
                return true;
            else
                return false;
        }

    }
}
